﻿<script setup lang="ts">
import { transformI18n } from '@/plugins/i18n'
import type { FormInstance } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useSystemConfigStoreWithOut } from '@/store/storage/systemConfigStore'
import { useUserInfoStoreWithOut } from '@/store/storage/userInfoStore'
import { getRandomImageUrl } from '@/utils'
import dayjs from 'dayjs'
import { useI18n } from 'vue-i18n'
import useLogout from '@/hooks/useLogout'
const ruleFormRef = ref<FormInstance>()
const router = useRouter()
const systemConfigStore = useSystemConfigStoreWithOut()
const { systemConfig } = storeToRefs(systemConfigStore)
const userInfoStore = useUserInfoStoreWithOut()
const { userInfo } = storeToRefs(userInfoStore)
const { Logout } = useLogout(router)
// 解锁点击事件
const unLock = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validateField('password', (valid) => {
    if (valid) {
      clearInterval(timer.value) // 清除壁纸切换定时器
      clearInterval(dateTimer.value) // 清除时间定时器
      systemConfig.value.isLockScreen = false
      systemConfigStore.setSystemConfigCache()
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 锁屏表单的字段控制
const sizeForm = reactive({
  password: '',
  setPassword: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
// 解锁屏幕密码的验证规则
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error(transformI18n('verifies.verifyPasswordEmpty', true)))
  } else {
    if (value !== systemConfig.value.lockScreenPassword) {
      callback(new Error(transformI18n('verifies.verifyPasswordError', true)))
    } else {
      callback()
    }
  }
}
// 设置锁屏密码、新密码的验证规则
const validateNewPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error(transformI18n('verifies.verifyPasswordEmpty', true)))
  } else {
    if (sizeForm.confirmPassword !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('confirmPassword', () => null)
    }
    callback()
  }
}
// 确认设置锁屏密码的验证规则
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error(transformI18n('verifies.verifyPasswordEmpty', true)))
  } else {
    if (lockScreenFormType.value === 'set') {
      if (value !== sizeForm.setPassword) {
        callback(new Error(transformI18n('verifies.verifyPasswordTwice', true)))
      } else {
        callback()
      }
    } else {
      if (value !== sizeForm.newPassword) {
        callback(new Error(transformI18n('verifies.verifyPasswordTwice', true)))
      } else {
        callback()
      }
    }
  }
}
// 锁屏表单各字段的验证规则
const rules = reactive({
  password: [{ validator: validatePassword }],
  setPassword: [{ validator: validateNewPassword }],
  oldPassword: [{ validator: validatePassword }],
  newPassword: [{ validator: validateNewPassword }],
  confirmPassword: [{ validator: validateConfirmPassword }]
})
// 锁屏表单显示隐藏控制字段
const isLockScreenFormShow = ref(false)
// 切换锁屏表单的显示隐藏
const toggleLockScreenForm = (e) => {
  isLockScreenFormShow.value = e
}
// 当前壁纸
const currentWallpaper = ref('')
// 手动切换壁纸的点击事件
const changeWallpaperHandle = () => {
  clearInterval(timer.value) // 清除壁纸切换定时器
  changeWallpaper()
  wallpaperInterval() // 启动壁纸切换定时器
}
// 壁纸切换获取当前壁纸的URL
const changeWallpaper = () => {
  currentWallpaper.value = getRandomImageUrl('')
}
// 默认锁屏后立即获取一张壁纸
changeWallpaper()
// 控制定时器开启关闭的字段
const timer = ref(0)
// 壁纸自动切换定时器
const wallpaperInterval = () => {
  timer.value = window.setInterval(changeWallpaper, 5 * 60 * 1000)// 5分钟切换一次壁纸
}
const { locale } = useI18n()
const nowDate = ref('')
const nowTime = ref('')
// 获取当前日期时间的方法
const getNowDateTime = () => {
  if (locale.value === 'zh') {
    nowDate.value = dayjs().format('YYYY年MM月DD日 dddd A')
    nowTime.value = dayjs().format('HH:mm:ss')
  } else if (locale.value === 'zh_tw') {
    nowDate.value = dayjs().format('YYYY年MM月DD日 dddd A')
    nowTime.value = dayjs().format('HH:mm:ss')
  } else {
    nowDate.value = dayjs().format('A dddd,MMMM D,YYYY')
    nowTime.value = dayjs().format('HH:mm:ss')
  }
}
// 默认锁屏后立即获取当前日期时间
getNowDateTime()
// 控制动态显示时间的定时器字段
const dateTimer = ref(0)
// 动态显示时间的定时器
const dateTimeInterval = () => {
  dateTimer.value = window.setInterval(getNowDateTime, 1000)
}
// 锁屏表单的类型字段
const lockScreenFormType = ref('')
onMounted(() => {
  wallpaperInterval()
  dateTimeInterval()
  // 判断当前应该展示锁屏的哪种表单
  if (systemConfig.value.lockScreenPassword === '') {
    lockScreenFormType.value = 'set' // 设置锁屏密码表单
  } else {
    lockScreenFormType.value = 'unlock' // 解锁屏幕表单
  }
})
// 修改锁屏密码按钮的点击事件
const changePasswordShow = () => {
  lockScreenFormType.value = 'change' // 修改锁屏密码表单
}
// 设置锁屏密码的确认事件
const setLockScreenPassword = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const fieldsToValidate = ['setPassword', 'confirmPassword']
  Promise.all(fieldsToValidate.map(item => {
    return new Promise((resolve, reject) => {
      formEl.validateField(item, (valid) => {
        resolve(valid)
        console.log(reject)
      })
    })
  })).then((data) => {
    console.log(data)
    if (!data.includes(false)) {
      systemConfig.value.lockScreenPassword = sizeForm.confirmPassword
      formEl.resetFields()
      systemConfigStore.setSystemConfigCache()
      lockScreenFormType.value = 'unlock'
    }
  })
}
// 取消修改密码按钮的点击事件
const cancelChangePassword = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  lockScreenFormType.value = 'unlock'
}
// 修改锁屏密码的确认事件
const changePassword = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const fieldsToValidate = ['oldPassword', 'newPassword', 'confirmPassword']
  Promise.all(fieldsToValidate.map(item => {
    return new Promise((resolve, reject) => {
      formEl.validateField(item, (valid) => {
        resolve(valid)
        console.log(reject)
      })
    })
  })).then((data) => {
    console.log(data)
    if (!data.includes(false)) {
      systemConfig.value.lockScreenPassword = sizeForm.confirmPassword
      formEl.resetFields()
      systemConfigStore.setSystemConfigCache()
      lockScreenFormType.value = 'unlock'
    }
  })
}
</script>

<template>
  <div class="vk-lock-screen">
    <div class="vk-lock-screen-background" :style="{ backgroundImage: 'url(' + currentWallpaper + ')' }"></div>
    <div :class="['vk-button-group', isLockScreenFormShow ? 'is-active' : '']">
      <span @click="toggleLockScreenForm(true)">{{ $t('buttons.buttonUnlockScreen') }}</span>
      <span @click="changeWallpaperHandle">{{ $t('buttons.buttonSwitchWallpaper') }}</span>
    </div>
    <div :class="['vk-date-time', isLockScreenFormShow ? 'is-active' : '']">
      <p>{{ nowTime }}</p>
      <p>{{ nowDate }}</p>
    </div>
    <div :class="['vk-lock-screen-operate', isLockScreenFormShow ? 'is-active' : '']">
      <span @click="toggleLockScreenForm(false)">{{ $t('buttons.buttonBack') }}</span>
      <span @click="Logout">{{ $t('buttons.buttonBackLogin') }}</span>
    </div>
    <div :class="['vk-lock-screen-form', isLockScreenFormShow ? 'is-active' : '']">
      <div class="vk-lock-screen-content">
        <el-avatar v-if="userInfo" class="vk-user-avatar" :size="180" :src="userInfo.avatar" />
        <p v-if="userInfo" class="vk-user-name">{{ userInfo.userName }}</p>
        <el-form ref="ruleFormRef" :model="sizeForm" :rules="rules">
          <el-form-item prop="password" v-if="lockScreenFormType === 'unlock'">
            <el-input class="vk-lock-screen-password" v-model="sizeForm.password" type="password" :placeholder="$t('placeholders.placeholderLockScreenPassword')" clearable show-password :validate-event="false" />
          </el-form-item>
          <el-form-item prop="setPassword" v-if="lockScreenFormType === 'set'">
            <el-input class="vk-lock-screen-password" v-model="sizeForm.setPassword" type="password" :placeholder="$t('placeholders.placeholderSetLockScreenPassword')" clearable show-password :validate-event="false" />
          </el-form-item>
          <el-form-item prop="oldPassword" v-if="lockScreenFormType === 'change'">
            <el-input class="vk-lock-screen-password" v-model="sizeForm.oldPassword" type="password" :placeholder="$t('placeholders.placeholderOldPassword')" clearable show-password :validate-event="false" />
          </el-form-item>
          <el-form-item prop="newPassword" v-if="lockScreenFormType === 'change'">
            <el-input class="vk-lock-screen-password" v-model="sizeForm.newPassword" type="password" :placeholder="$t('placeholders.placeholderNewPassword')" clearable show-password :validate-event="false" />
          </el-form-item>
          <el-form-item prop="confirmPassword" v-if="lockScreenFormType === 'change' || lockScreenFormType === 'set'">
            <el-input class="vk-lock-screen-password" v-model="sizeForm.confirmPassword" type="password" :placeholder="$t('placeholders.placeholderConfirmPassword')" clearable show-password :validate-event="false" />
          </el-form-item>
          <el-form-item :class="['vk-lock-screen-button-group', lockScreenFormType === 'change' || lockScreenFormType === 'unlock' ? 'is-change' : '']">
            <el-button v-if="lockScreenFormType === 'unlock'" text type="primary" @click="changePasswordShow">
              {{
                $t('buttons.buttonChangePassword') }}
            </el-button>
            <el-button v-if="lockScreenFormType === 'unlock'" type="primary" @click="unLock(ruleFormRef)">
              {{
                $t('buttons.buttonUnlock') }}
            </el-button>
            <el-button v-if="lockScreenFormType === 'set'" type="primary" @click="setLockScreenPassword(ruleFormRef)">
              {{
                $t('buttons.buttonConfirm') }}
            </el-button>
            <el-button v-if="lockScreenFormType === 'change'" text type="primary" @click="cancelChangePassword(ruleFormRef)">{{ $t('buttons.buttonCancel') }}</el-button>
            <el-button v-if="lockScreenFormType === 'change'" type="primary" @click="changePassword(ruleFormRef)">
              {{
                $t('buttons.buttonConfirm') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.vk-lock-screen {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 8000;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
  backdrop-filter: blur(8px);

  &::before {
    position: absolute;
    inset: 0;
    background-color: var(--el-fill-color-blank);
    opacity: 0.7;
    content: '';
  }

  .vk-lock-screen-background {
    position: absolute;
    inset: 0;
    z-index: 4;
    background-position: center center;
    background-size: cover;
    background-attachment: fixed;
  }

  .vk-date-time {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 5;
    padding: 0 0 60px 60px;
    transition: bottom 0.28s;

    &.is-active {
      bottom: 100vh;
    }

    p {
      margin: 0;
      color: var(--el-color-white);
      font-size: 108px;
      line-height: 1.2;

      span {
        margin-right: 10px;
        font-size: 32px;
      }
    }

    p+p {
      font-size: 32px;
    }
  }

  .vk-lock-screen-operate,
  .vk-button-group {
    position: absolute;
    right: 0;
    display: inline-block;
    padding: 20px;
    transition: top 0.28s;

    span {
      display: inline-block;
      height: 36px;
      padding: 0 20px;
      color: var(--el-color-white);
      font-size: 14px;
      line-height: 34px;
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.6);
      border-radius: 36px;
      cursor: pointer;
    }

    span+span {
      margin-left: 20px;
    }
  }

  .vk-lock-screen-operate {
    top: -100px;
    z-index: 8;

    &.is-active {
      top: 0;
    }

  }

  .vk-button-group {
    top: 0;
    z-index: 5;

    &.is-active {
      top: -100px;
    }
  }

  .vk-lock-screen-form {
    position: absolute;
    inset: 0;
    z-index: 2;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    opacity: 0;
    backdrop-filter: blur(15px);
    transition: opacity 0.56s, z-index 0.56s;

    &.is-active {
      z-index: 6;
      opacity: 1;

      &::before {
        position: absolute;
        inset: 0;
        background-color: var(--el-fill-color-blank);
        opacity: 0.4;
        content: '';
      }
    }
  }

  .vk-lock-screen-content {
    position: relative;
    z-index: 2;
    padding: 40px;

    .vk-user-avatar {
      display: block;
      margin: 0 auto;
    }

    .vk-user-name {
      margin: 15px auto;
      color: var(--el-text-color-primary);
      font-size: 16px;
      text-align: center;
    }

    .vk-lock-screen-password {
      width: 300px;
    }

    .vk-lock-screen-button-group {
      :deep(.el-form-item__content) {
        justify-content: center;
      }

      &.is-change {
        :deep(.el-form-item__content) {
          justify-content: flex-end;
        }

      }
    }
  }
}
</style>
